package com.sky.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.service.user.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
@Slf4j
@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MerchantMapper merchantMapper;
    @Value("${wechat.appid}")
    private String appId;
    @Value("${wechat.secret}")
    private String secret;
    private static final String grantType = "authorization_code";
    private static final String url = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 用户登录
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //用户登录，完成自动注册
        //1.从微信端获取openid
        String openId = getAppId(userLoginDTO.getCode());
        //判断openid是否为空
        if (!StringUtils.hasText(openId)){
           throw new BaseException("未获取到openId");
        }
        //2.根据openid从数据库查询用户是否已经存在
        User user = userMapper.getByOpenid(openId);
        //3.如果不存在，就自动注册
        if (user == null){
             user = new User();
             user.setCreateTime(LocalDateTime.now());
             user.setOpenid(openId);
             userMapper.insert(user);
        }
        //4.生成token
        HashMap<String , Object> map = new HashMap<>();
        map.put("openId",openId);
        map.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        //获取商家信息
        Merchant merchant =merchantMapper.getById(1L);
        //计算费用
        String lnglat = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal cost = MapUtils.getDelivoryCost(lnglat, userLoginDTO.getLocation());
        //5.构造返回结果
        UserLoginVO loginVO = UserLoginVO.builder().token(token)
                .shopTelephone(merchant.getShopTelephone())
                .shopName(merchant.getShopName())
                .shopAddress(merchant.getShopAddress())
                .deliveryFee(cost)
                .shopId(merchant.getId())
                .openid(openId)
                .build();
        return loginVO;
    }
    /**
     * 该方法用于获取用户登录的appId
     */
    private String getAppId(String code){
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type", grantType);
        //响应值
        String s = HttpClientUtil.doGet(url, map);
        log.info("微信登录返回：{}",s);
        //解析响应值
        JSONObject jsonObject = JSONObject.parseObject(s);
        String openid =(String) jsonObject.get("openid");
        return openid;
    }
}
